package com.alone.wchat.wxBackend.utils;


import java.text.SimpleDateFormat;
import java.util.*;

public class TimeUtils {

	/**
	 * 将日期转为制定格式的字符串
	 * 
	 * @param date
	 *            日期对象
	 * @param pattern
	 *            日期字符串模式
	 * @return 格式化后的日期
	 *
	 */
	public static String getDateStr(Date date, String pattern) {
		SimpleDateFormat sf = new SimpleDateFormat(pattern);
			return sf.format(date);
	}

	/**
	 * 获取当前时间
	 *
	 * */

	public static  String getSystemTime(){
		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));    //获取东八区时间
		SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
		String curDate = s.format(c.getTime());  //当前日期
		return curDate;
	}

	/**
	 * 获取城市所在时区
	 * @param targetId 目标时区id 比如：America/New_York
	 * @return string 时区 比如：+08:00
	 */
	public static String getTimeZone(String targetId){
		//校验入参是否合法
		if (null == targetId || "".equals(targetId)){
			return null;
		}

		try {
			TimeZone timeZone = TimeZone.getTimeZone(targetId);
			SimpleDateFormat outputFormat = new SimpleDateFormat("Z");
			outputFormat.setTimeZone(timeZone);
			Date date = new Date(System.currentTimeMillis());

			//加上冒号显示，把+0800转成+08:00
			StringBuffer stringBuffer = new StringBuffer(outputFormat.format(date));
			return stringBuffer.insert(3, ":").toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getFormatedDateString(float timeZoneOffset) {
		if (timeZoneOffset > 13 || timeZoneOffset < -12) {
			timeZoneOffset = 0;
		}
		int newTime = (int) (timeZoneOffset * 60 * 60 * 1000);
		TimeZone timeZone;
		String[] ids = TimeZone.getAvailableIDs(newTime);
		if (ids.length == 0) {
			timeZone = TimeZone.getDefault();
		} else {
			timeZone = new SimpleTimeZone(newTime, ids[0]);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(timeZone);
		return sdf.format(new Date());
	}

	/**
	 * 获取城市所在当地时间
	 *
	 *
	 * */

	public static String getLocalDatetimeString(String local) {
		Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(local));
		cal.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
		String date = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
		String time = cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);
		return date + " " + time;
	}


	public static void main(String[] args) {
		System.out.println(getTimeZone("America/Los_Angeles"));
		System.out.println(getLocalDatetimeString("+7:00"));
		//System.out.println(getFormatedDateString());
	}

}
